/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package elementsDefense.enemies;

import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Spatial;
import com.jme3.scene.control.AbstractControl;
import com.jme3.scene.control.Control;
import elementsDefense.Main;
import elementsDefense.map.Map.Dir;
import elementsDefense.map.Tile;

/**
 *
 * @author Ricardo
 */
public class NavigationControl extends AbstractControl{
    BasicEnemy owner;
    
    Tile currentTile;
    Tile nextTile;
    Vector3f targetPos;
    Vector3f direction;
    private float velocity=1;

    public NavigationControl(BasicEnemy owner) {
        this.owner =owner;
    }
    
    @Override
    protected void controlUpdate(float tpf) {
        Tile cuTile = getTile();
        if(cuTile!=currentTile){
            if(cuTile.type==Tile.END){
                owner.sucess();
                return;
            }else{
                double rand=Math.random();
                double rand2=Math.random();
                float var=(float) ((rand-0.5)/7);
                float var2=(float) ((rand2-0.5)/7);
                currentTile=cuTile;
                nextTile = Main.map.getTileAt(currentTile,currentTile.nextTiles.get((int)(rand*currentTile.nextTiles.size())) );
                targetPos = new Vector3f(nextTile.x+0.5f+var, 0, nextTile.y+0.5f+var2);
                direction = targetPos.subtract(spatial.getLocalTranslation()).normalizeLocal();
                spatial.lookAt(targetPos, Vector3f.UNIT_Y);
            }
        }
        spatial.move(direction.mult(velocity*tpf));
    }

    public void setVelocity(float velocity) {
        this.velocity = velocity;
    }
    
    @Override
    protected void controlRender(RenderManager rm, ViewPort vp) {
    }

    public Control cloneForSpatial(Spatial spatial) {
        final NavigationControl control = new NavigationControl(owner);
        /* Optional: use setters to copy userdata into the cloned control */
        // control.setIndex(i); // example
        control.setSpatial(spatial);
        return control;
    }
    
    public Tile getTile(){
        return Main.map.tile[(int)spatial.getLocalTranslation().x][(int)spatial.getLocalTranslation().z];
        
    }
    
}
